import axios, { AxiosError, AxiosInstance, AxiosResponse } from "axios";
import { Toast } from "@/app/components/Toast";
import { BASE_URL, SIG } from "@/utils/env";
import { sortParams } from "@/utils/tool";
import crypto from "crypto";

const instance: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

console.log("SIG:", SIG);

function generateSignature(
  params: Record<string, any> = {},
  secret: string
): string {
  console.log("params:", params); // 打印 params
  console.log("secret:", secret); // 打印 secret
  if (!params || typeof params !== "object") {
    throw new Error("Invalid parameters for signature generation");
  }

  const sortedParams = sortParams(params);
  console.log("sortedParams:", sortedParams); // 打印排序后的参数
  return crypto.createHmac("sha256", secret).update(sortedParams).digest("hex");
}

// 错误处理函数
function handleError(error: AxiosError): void {
  let msg = error.message;
  if (error.code === "ECONNABORTED") {
    msg = "Network exception.. Please try again.";
  }
  Toast.center(msg);
}

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse): Promise<AxiosResponse> => {
    const { data } = response;
    if (data?.code === 0) {
      return Promise.resolve(response.data);
    } else {
      Toast.center(data?.msg);
      return Promise.reject(data);
    }
  },
  (error: AxiosError): Promise<AxiosError> => {
    handleError(error);
    return Promise.reject(error);
  }
);

type Method = "get" | "post" | "put" | "delete" | "patch";

export default async function request(
  url: string,
  params: Record<string, any> = {},
  method: Method
): Promise<AxiosResponse> {
  const newParams = {
    public: {
      sig: generateSignature(params, SIG),
      nonce: Date.now(),
    },
    params,
  };

  return instance.request({
    url,
    method,
    data: ["put", "post", "delete", "patch"].includes(method.toLowerCase())
      ? newParams
      : undefined,
    params: !["put", "post", "delete", "patch"].includes(method.toLowerCase())
      ? newParams
      : undefined,
  });
}
